using System.Collections.Generic;
using System.Linq;
using Engine.Core.Interfaces;
using Microsoft.Xna.Framework;

namespace Engine.Core.Engines {
    public class PhysicsEngine : IPhysicsEngine {

        public float Gravity { get; set; }

        private readonly List<IPhysicElement> _physicElements;
        public List<IPhysicElement> PhysicElements { get { return _physicElements; } }

        public PhysicsEngine() {
            Gravity = .981f;
            _physicElements = new List<IPhysicElement>();
        }

        public void Apply() {

            foreach (var el in PhysicElements) {

                if (el.Position.Y >= 400 || (el.Position.Y + .981f) > 400) {
                    el.Position = new Vector2(el.Position.X, 400);
                    continue;
                }

                var fallgeschwindigkeit = 9.81f * el.Lifetime / 1000;

                UpdatePosition(el,fallgeschwindigkeit);

                el.Position += new Vector2(0, fallgeschwindigkeit);

                var acclDegenerationRightMovement = el.Acceleration + new Vector2(-.02f, 0);
                var acclDegenerationLeftMovement = el.Acceleration + new Vector2(.02f, 0);


                if (acclDegenerationRightMovement.X >= 0) {
                    el.Acceleration = acclDegenerationRightMovement;
                }
                else if (acclDegenerationLeftMovement.X <= 0)
                {
                    el.Acceleration = acclDegenerationLeftMovement;
                }

            }
            PhysicElements.Clear();
        }

        private void UpdatePosition(IPhysicElement el, float fallgeschwindigkeit)
        {
            var newPos = el.Position + el.Acceleration;
            newPos += new Vector2(0, fallgeschwindigkeit);

            if (newPos.Y >= 400)
                el.Position = new Vector2(newPos.X, 400);
            else
            {
                el.Position = newPos;
            }
        }

        public void AddPhysicElements(IEnumerable<IPhysicElement> elements ) {
            _physicElements.AddRange(elements.ToList());
        }
    }
}